import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter_uxin/Compontents/http_Dio/http_manager.dart';
import 'package:flutter_uxin/Compontents/http_Dio/result_data.dart';
import 'package:flutter_uxin/Compontents/http_Dio/address.dart';

import 'package:flutter_uxin/Login/Parsers/YxAreaParse.dart';
import 'package:flutter_uxin/Login/Parsers/areaDNS.dart';

import 'package:shared_preferences/shared_preferences.dart';

import 'package:gbk_codec/gbk_codec.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class areaSelectPage extends StatefulWidget {
  areaSelectPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _areaSelectPageState createState() => _areaSelectPageState();
}

class _areaSelectPageState extends State<areaSelectPage> {
//  List <YXArea> allAreaList;
  List<Choice> topList;
  var _futureBuilderFuture;
  bool _loading = false;

//请求全国区域列表
  Future<ResultData> areaRequest() async {
    ResultData res =
        await HttpManager.getInstance().get(Address.YxArea_API, null);
//    if(res.isSuccess){
//      setState(() {
//        String str = res.data.toString();
//        print('str----------------------$str');
//        List responseJson = jsonDecode(str);
//        List <YXArea> areaList = responseJson.map((m) => new YXArea.fromJson(m,null,YXAreaType.stateType)).toList();
////        allAreaList.clear();
////        allAreaList.addAll(areaList);
//          return  areaList;
//      });
//    }
    return res;
  }

//根据区域请求负载
  Future loadRequestWithAreaId(String areaId) async {
    ResultData res = await HttpManager.getInstance().get(
        Address.url_get_dns,
        {
          "id": '$areaId',
        },
        responseType: ResponseType.bytes);
//    ResultData res = await HttpManager.getInstance().get('${Address.url_get_dns}?id=$areaId',null);
//    print('res.data----------------------${res.data}');
    if (res.isSuccess) {
      setState(() {
        _loading = false;
        String str = gbk_bytes.decode(res.data);
        print('str----------------------$str');
        List responseJson = jsonDecode(str);
        List<areaDNS> areaList =
            responseJson.map((m) => new areaDNS.fromJson(m)).toList();
        areaDNS area = areaList.first;
        saveAreaDNS(area);
        Navigator.pop(context, area);
//          print('areaName----------------------$area.areaName');
//        print('str----------------------$str');
      });
    } else {
      setState(() {
        _loading = false;
      });
    }
  }

  void saveAreaDNS(areaDNS area) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> map = area.toJson();
    String jsonString = jsonEncode(area);
    print('jsonString----------------$jsonString');
    prefs.setString('areaDNS', jsonString);

    map.forEach((key, value) {
      String newKey = 'areaDNS_$key';
      prefs.setString(newKey, value);
    });

//    prefs.setMockInitialValues(str);
  }

  void areaOnTap(YXArea area) {
    if (area.areaList == null ||
        area.areaList.length == 0 ||
        area.areaType == YXAreaType.areaType) {
//      print('开始请求------loadRequestWithAreaId');
      String requestID = '';
      if (area.area_id != null) {
        requestID = area.area_id;
      } else if (area.city_id != null) {
        requestID = area.city_id;
      } else if (area.state_id != null) {
        requestID = area.city_id;
      }

      setState(() {
        _loading = true;
      });
      loadRequestWithAreaId(requestID);
    } else {
      changeTopList(area);
    }
  }

//头部列表数据更改
  void changeTopList(YXArea area) {
    setState(() {
      topList.clear();
      if (area.areaType == YXAreaType.stateType) {
        Choice choice = new Choice(title: area.state_name, id: area.state_id);
        topList.add(choice);
      } else if (area.areaType == YXAreaType.cityType) {
        Choice choice_1 = new Choice(title: area.state_name, id: area.state_id);
        topList.add(choice_1);

        Choice choice_2 = new Choice(title: area.city_name, id: area.city_id);
        topList.add(choice_2);
      } else if (area.areaType == YXAreaType.areaType) {
        Choice choice_1 = new Choice(title: area.state_name, id: area.state_id);
        topList.add(choice_1);

        Choice choice_2 = new Choice(title: area.city_name, id: area.city_name);
        topList.add(choice_2);

        Choice choice_3 = new Choice(title: area.area_name, id: area.area_id);
        topList.add(choice_3);
      }
    });
  }

  void initState() {
    super.initState();
    topList = new List<Choice>();

    ///用_futureBuilderFuture来保存_gerData()的结果，以避免不必要的ui重绘
    _futureBuilderFuture = areaRequest();
//    allAreaList = new List<YXArea>();
//    areaRequest();
  }

  //当整个页面dispose时，记得把控制器也dispose掉，释放内存
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
//        backgroundColor:Colors.red,
        title: const Text('请选择区域'),
      ),
      body: ModalProgressHUD(child: _buildWidget(), inAsyncCall: _loading),
    );
  }

  Widget _buildWidget() {
    return new Form(
      child: new Column(
        children: <Widget>[
          new Container(
              height: 30,
              color: Color(0xFFE3F2FD),
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: topList.length == null ? 0 : topList.length,
                separatorBuilder: (BuildContext context, int index) => Icon(
                  Icons.arrow_forward_ios,
                  size: 14,
                ), //index为偶数，创建绿色分割线；index为奇数，则创建红色分割线
                itemBuilder: (BuildContext context, int index) => new Container(
                    width: 60,
                    height: 30,
                    color: Colors.transparent,
                    child: Center(
                      child: Text("${topList[index].title}"),
                    )),
                //创建子Widget
              )),
          new Expanded(
            flex: 1,
            child: Container(
              child: FutureBuilder<ResultData>(
                future: _futureBuilderFuture,
                builder: _buildFuture,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }

        ResultData res = snapshot.data;
        if (res.isSuccess) {
          String str = res.data.toString();
//          print('str----------------------$str');
          List responseJson = jsonDecode(str);
          List<YXArea> areaList = responseJson
              .map((m) => new YXArea.fromJson(m, null, YXAreaType.stateType))
              .toList();
          return areaListPage(
            areaList,
            onTap: (area) {
              areaOnTap(area);
            },
          );
        }
        print('snapshot---------------$snapshot');
        return Container();
      default:
        return null;
    }
  }
}

class Choice {
  const Choice({this.title, this.id});
  final String title;
  final String id;
}

class areaListPage extends StatefulWidget {
//  areaListPage({Key key, this.areaList ,this.onTap}) : super(key: key);
  areaListPage(this.areaList, {this.onTap});

  @required
  ValueChanged<YXArea> onTap;
  final List<YXArea> areaList;
  @override
  _areaListPageState createState() => _areaListPageState();
}

class _areaListPageState extends State<areaListPage> {
  List<YXArea> newAreaList;

  void initState() {
    super.initState();
    newAreaList = new List<YXArea>();
//    print('widget.areaList----------------${widget.areaList}');
    newAreaList.addAll(widget.areaList);
  }

  //当整个页面dispose时，记得把控制器也dispose掉，释放内存
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Center(
        child: ListView.separated(
            itemCount: newAreaList.length == null ? 0 : newAreaList.length,
            separatorBuilder: (BuildContext context, int index) => Divider(
                color: Colors.grey), //index为偶数，创建绿色分割线；index为奇数，则创建红色分割线
            itemBuilder: (BuildContext context, int index) => ListTile(
                  title: Text("${newAreaList[index].name}"),
                  onTap: () {
                    YXArea area = newAreaList[index];
                    widget.onTap(area);
                    if (area.areaList != null) {
                      setState(() {
                        newAreaList.clear();
                        newAreaList.addAll(area.areaList);
                      });
                    }
                  },
                ) //创建子Widget
            ));
  }
}
